package cn.cymym.control;

import java.io.IOException;
import java.lang.reflect.Method;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cymym.comm.BeingRadom;
import cn.cymym.comm.CommException;
import cn.cymym.comm.MyMd5Util;
import cn.cymym.comm.PwdMd5;
import cn.cymym.comm.VerificationCode;
import cn.cymym.domain.User;
import cn.cymym.service.UserService;

@WebServlet(urlPatterns= {"/register.do","/getCode.do","/login.do","/updateUserInfo.do"})
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(UserServlet.class);
    private UserService userService = new UserService();
    private MyMd5Util mUtil = new MyMd5Util();
    //用户编码
	private BeingRadom beingRadom = new BeingRadom();
    public UserServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String servletPath = request.getServletPath();
		String methodname = servletPath.substring(1);
		methodname = methodname.substring(0,methodname.length()-3);
		logger.debug(methodname);
		try {
			Method method = getClass().getDeclaredMethod(methodname, HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(this, request,response);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CommException("方法没有找到");
		}
		
	}
	public void getCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {  
        resp.setHeader("Pragma", "No-cache");    
        resp.setHeader("Cache-Control", "no-cache");    
        resp.setDateHeader("Expires", 0);    
        resp.setContentType("image/jpeg");    
            
        //生成随机字串    
        String verifyCode = VerificationCode.generateVerifyCode(4);  
        //存入会话session    
        HttpSession session = req.getSession(true);    
        session.setAttribute("verify_code", verifyCode.toLowerCase());    
        //生成图片    
        int w = 75, h = 36;  
        VerificationCode.outputImage(w, h, resp.getOutputStream(), verifyCode, resp);  
    }  
	protected void register(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
		String tel = request.getParameter("tel");
		String verifyCode = request.getParameter("verifyCode");
		String pwd = request.getParameter("pwd");
		String confirmPwd = request.getParameter("confirmPwd");
		String xieyi = request.getParameter("xieyi");
		
		logger.debug(tel+" "+verifyCode+" "+pwd+" "+confirmPwd+" "+xieyi);
		
		HttpSession session = request.getSession();
		String verify_code = (String) session.getAttribute("verify_code");
		
		logger.debug("真实验证码："+verify_code);
		
		
		long index = userService.isExsit(tel);
		if (index > 0) {
			logger.info("该账户已存在！");
			request.setAttribute("account_msg", "该账户已存在！");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		} else {
			if (verifyCode.equalsIgnoreCase(verify_code)) {
				if (pwd.equals(confirmPwd)) {
					if (xieyi.equals("1")) {
						try {
							String pwdDb =  mUtil.getEncryptedPwd(pwd);
							User user = new User(beingRadom.BeingDate(),tel, pwdDb);
							userService.register(user);
							logger.info("注册成功");
							request.getRequestDispatcher("/sign.jsp").forward(request, response);
						} catch (NoSuchAlgorithmException e) {
							e.printStackTrace();
						}
					} else {
						logger.info("协议没同意");
						request.setAttribute("xieyi_msg", "请同意该协议！");
						request.getRequestDispatcher("/register.jsp").forward(request, response);
					}
				} else {
					logger.info("两次密码输入不相同！");
					request.setAttribute("pwd_msg", "两次密码输入不相同！");
					request.getRequestDispatcher("/register.jsp").forward(request, response);
				}
			} else {
				logger.info("验证码输入错误");
				request.setAttribute("verify_msg", "验证码输入错误");
				request.getRequestDispatcher("/register.jsp").forward(request, response);
			}
		}
	}
	
	protected void login(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
	{
		String tel = request.getParameter("tel");
		String pwd = request.getParameter("pwd");
		
		HttpSession session = request.getSession();
		
		logger.info(tel+" "+pwd+" ");
		User user = userService.getTelAndPwd(tel);
		if (user != null) {
			try {
				if (mUtil.validPassword(pwd, user.getPwd())) {
					logger.info("登陆成功");
					logger.info(user.getUserNumber());
					session.setAttribute("userName", user.getName());
					session.setAttribute("userCode", user.getUserNumber());
					session.setAttribute("usertel", user.getTel());
					request.getRequestDispatcher("/index.jsp").forward(request, response);
				}else {
					logger.info("密码输入错误");
					request.setAttribute("login_pwd_msg", "密码输入错误");
					request.getRequestDispatcher("/sign.jsp").forward(request, response);
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		} else {
			logger.info("账户输入错误");
			request.setAttribute("login_tel_msg", "账户输入错误");
			request.getRequestDispatcher("/sign.jsp").forward(request, response);
		}
		
	}
	protected void updateUserInfo(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
		String userName = request.getParameter("userName");
		String YYYY = request.getParameter("YYYY");
		String MM = request.getParameter("MM");
		String DD = request.getParameter("DD");
		String gender = request.getParameter("gender");
		String tel = request.getParameter("tel");
		String qq = request.getParameter("qq");
		String email = request.getParameter("email");
		
		HttpSession session = request.getSession();
		
		//处理数据 日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
		String datestr = YYYY+"-"+MM+"-"+DD;
		logger.info(datestr);
		try {
			Date birthday = sdf.parse(datestr);
			User user = new User(userName, tel, email, qq, gender, birthday,(String)session.getAttribute("userCode"));
			userService.updateUserInfo(user);
			request.getRequestDispatcher("/grxx.jsp").forward(request, response);
		} catch (ParseException e) {
			e.printStackTrace();
			logger.debug("日期没有转换成功");
		}
	}

}
